﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandClear.Util.Caching;
using thousandClear.Util.Encryption;
using thousandClear.Util.Setting;
using thousandClear.Areas.Admin.Models;
using thousandclear.Data;

namespace thousandClear.Areas.Admin.Controllers
{
    public class UserController : BaseController
    {
        private qianjingEntities _db;
        // GET: Admin/Login
        public ActionResult Login()
        {
            HttpCookie cookie = ControllerContext.HttpContext.Request.Cookies.Get("SessionId");

            if (cookie != null)
            {
                HttpCookie mycookie;
                mycookie = Request.Cookies["SessionId"];
                TimeSpan ts = new TimeSpan(0, 0, 0, 0);//时间跨度 
                mycookie.Expires = DateTime.Now.Add(ts);//立即过期 
                Response.Cookies.Remove("SessionId");//清除 
                Response.Cookies.Add(mycookie);//写入立即过期的*/
                Response.Cookies["SessionId"].Expires = DateTime.Now.AddDays(-1);

            }

            ViewBag.Title = "用户登录";
            ViewBag.Success = true;
            return View();
        }
        [HttpPost]
        // POST: Admin/Login
        public ActionResult Login(string username, string password)
        {
            AppSetting setting = new AppSetting();
            ClearCookie();
            if (username == setting.AdminAccount && password == setting.AdminPassword)
            {
                string sessionId = Guid.NewGuid().ToString();

                SetCookie("SessionId", sessionId);

                CacheProvider.Set(sessionId, new AdminCacheData
                {
                    LoginStatus = true
                }, 120);

                return RedirectToAction("Index", "Main");
            }
            else
            {

                using (_db = new qianjingEntities())
                {

                    var record = _db.O_User.FirstOrDefault(a => a.ouAccount == username && a.ouPassword == password);
                    if (record != null)
                    {
                        string sessionId = Guid.NewGuid().ToString();
                        SetCookie("level", record.ouLevel.ToString());
                        SetCookie("SessionId", sessionId);
                        SetCookie("uid", record.ouAccount.ToString());

                        CacheProvider.Set(sessionId, new AdminCacheData
                        {
                            LoginStatus = true
                        }, 120);


                        return RedirectToAction("Index", "Main");
                    }
                }


                ViewBag.Success = false;
                ViewBag.ErrMsg = "登录失败";

                return View();
            }
        }

        // GET: Admin/User
        public ActionResult Index(int? page, int? count)
        {
            string level = "1";
            level = GetCookie("level");
            ViewBag.level = level;
            List<UserModel> list = new List<UserModel>();

            if (page == null)
            {
                page = 1;
            }

            if (count == null)
            {
                count = 10;
            }

            int totalCount = 0;
            int totalPage = 1;
            int currentPage = page.Value;
            int pageCount = count.Value;


            List<O_User> records = null;


            using (_db = new qianjingEntities())
            {
                totalCount = _db.O_User.Count();

                records = _db.O_User.OrderBy(a => a.OUID).Where(a => a.RowStatus == 1).Skip((page.Value - 1) * count.Value).Take(count.Value).ToList();
            }

            if (records != null)
            {
                foreach (var item in records)
                {
                    list.Add(new UserModel
                    {
                        OUID = Convert.ToInt16(item.OUID),
                        ouAccount = item.ouAccount,
                        ouPassword = item.ouPassword,
                        CreatedDate = item.CreatedDate.ToString("yyyy - MM - dd HH: mm")
                    });
                }
            }

            ViewBag.TotalCount = totalCount;
            totalPage = int.Parse((totalCount / count).ToString()) + (totalCount % count == 0 ? 0 : 1);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            ViewBag.PageCount = pageCount;

            if (page <= 1)
            {
                ViewBag.PrevPageUrl = string.Format("../admin/user?page={0}&count={1}", page, count);
            }
            else
            {
                ViewBag.PrevPageUrl = string.Format("../admin/user?page={0}&count={1}", page - 1, count);
            }

            if (page >= totalPage)
            {
                ViewBag.NextPageUrl = string.Format("../admin/user?page={0}&count={1}", page, count);
            }
            else
            {
                ViewBag.NextPageUrl = string.Format("../admin/user?page={0}&count={1}", page + 1, count);
            }



            ViewBag.Title = "用户管理";
            return View(list);
        }
        public ActionResult Edit(int id)
        {
            ViewBag.Success = true;

            ViewBag.Id = id;
            ViewBag.TypedPwd = string.Empty;
            ViewBag.RetypedPwd = string.Empty;

            using (_db = new qianjingEntities())
            {
                var record = _db.O_User.FirstOrDefault(a => a.OUID == id);

                if (record != null)
                {
                    ViewBag.Account = record.ouAccount;
                }
            }

            return View();
        }

        [HttpPost]
        public ActionResult Edit(string data)
        {
            ViewBag.Success = true;

            var post = JObject.Parse(data);

            long id = post["id"].Value<long>();
            string account = post["account"].Value<string>();
            string typedPwd = post["typedPwd"].Value<string>();
            string retypedPwd = post["retypedPwd"].Value<string>();

            using (_db = new qianjingEntities())
            {
                var records = _db.O_User.FirstOrDefault(a => a.OUID == id);

                if (records != null)
                {
                    records.ouPassword = typedPwd;
                    records.UpdatedDate = DateTime.Now;
                }

                _db.SaveChanges();
            }

            return RedirectToAction("Index");
        }
        // GET: Admin/User/Add
        public ActionResult Add()
        {
            ViewBag.Success = true;
            ViewBag.Account = string.Empty;
            ViewBag.TypedPwd = string.Empty;
            ViewBag.RetypedPwd = string.Empty;

            return View();
        }

        [HttpPost]
        public ActionResult Add(string data)
        {

            var post = JObject.Parse(data);
            ViewBag.Success = true;
            string account = post["account"].Value<string>();
            string typedPwd = post["typedPwd"].Value<string>();
            string retypedPwd = post["retypedPwd"].Value<string>();

            ViewBag.Account = account;
            ViewBag.TypedPwd = typedPwd;
            ViewBag.RetypedPwd = retypedPwd;

            using (_db = new qianjingEntities())
            {
                var record = _db.O_User.FirstOrDefault(a => a.ouAccount == account);

                if (record != null)
                {
                    ViewBag.Success = false;
                    ViewBag.ErrMsg = "该账号已存在";
                    return View();
                }

                _db.O_User.Add(new O_User
                {
                    ouAccount = account,
                    ouPassword = typedPwd,
                    CreatedDate = DateTime.Now,
                    UpdatedDate = DateTime.Now,
                    CreatedBy = "yourself",
                    RowStatus = 1,
                });

                _db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public bool CheckLoginStat()
        {
            return CheckLogin();
        }
    }
}